import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wk_weather/bean/MyRouter.dart';
import 'package:wk_weather/bean/CityInfo.dart';
import 'package:wk_weather/myconfig/ViewState.dart';
import 'package:wk_weather/utils/DialogTool.dart';
import 'package:wk_weather/utils/MyLogTool.dart';
import 'package:wk_weather/utils/SharedPreferenceTool.dart';
import 'package:wk_weather/utils/ToastUtils.dart';
import 'package:wk_weather/bloc/city/city_bloc.dart';
import 'package:wk_weather/views/MyApp.dart';
import 'package:wk_weather/views/widget/StateView.dart';
import 'package:wk_weather/views/pages/home/MainAppBar.dart';
import 'package:wk_weather/views/pages/home/MainMessage.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:location_permissions/location_permissions.dart';
import 'package:wk_weather/views/widget/WeatherMainBg.dart';


class HomePage extends StatefulWidget {

  HomePage({Key key}) : super(key:key);

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin{
  var locationState;

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context);

    var updateDest ="本次更新：\r\n 没更新，就是想弹个弹窗。" ;
    showOTADialog("https://wppkg.baidupcs.com/issue/netdisk/apk/BaiduNetdisk_11.3.2.apk", updateDest, "1.0.20201112");

    var rootView = Stack(
      children: [
        // 天气背景
        WeatherMainBg(),

        Container(
            padding: EdgeInsets.only(  top: MediaQueryData.fromWindow(WidgetsBinding.instance.window).padding.top),
            child: BlocBuilder<CityBloc, CityState>(
              builder: ( content, state) {
                // todo  主页面状态
                weatherPrint( '主页面状态， state: ${state.runtimeType}, locationState: $locationState');

                if (state is CitySuccess) {
                  print("城市读取成功，直接返回了");
                  return _buildHomeContent(state.cityModels);
                }

                else if (state is CityInit) {
                  if (locationState == null) {
                    locationState = LocatePermissionState.loading;
                    requestPermission();
                  }

                  else if (locationState == LocatePermissionState.success) {
                    // todo 发出定位请求
                    print("发出定位请求");
                    BlocProvider.of<CityBloc>(context).add(RequestLocationEvent());
                  }
                  return Container(
                    alignment: Alignment.center,
                    child: Container(),
                  );
                }

                else if (state is LocationSuccessState) {
                  return Container(
                    alignment: Alignment.center,
                    child: Container(),
                  );
                }
                return StateView(weatherState: ViewState.loading);
              },
            )),
      ],
    );
    DateTime _lastPressedAt= DateTime(2000, 1, 2);

    // todo  WillPopScope 拦截点击事件 ， 双击退出
    var exitView =WillPopScope(
      onWillPop: () async {
        // difference 是对两个日期进行比较
        if ( DateTime.now().difference(_lastPressedAt) > Duration(seconds: 2)) {
          _lastPressedAt = DateTime.now();
          ToastUtils.toastMsg("双击退出", globalKey.currentContext, duration: 1);
          return false ;
        } else {
          // 停止定位
          await AmapLocation.instance.stopLocation();
          SystemNavigator.pop(animated: true); // 直接退出APP
          return true ;
        }

      },
      child: rootView ,
    );


    return Scaffold(
      body: exitView,
    );
  }


  Widget _buildHomeContent(List<CityModel> cityModels) {
    weatherPrint("build home content: ${cityModels?.length}");
    return Column(
      children: [

        MainAppBar( cityModels: cityModels),
        // 主页 详情部分
        Expanded(
          child: MainMessage(),
        )
      ],
    );
  }

  Future<void> requestPermission() async {
    // todo 申请定位权限
    print("申请定位请求---------------");
    await Future.delayed(Duration(seconds: 2));
    var permissionStatus = await LocationPermissions().checkPermissionStatus();
    weatherPrint('当前权限状态：$permissionStatus');
    if (permissionStatus != PermissionStatus.granted) {
      var permissionResult = await LocationPermissions().requestPermissions(permissionLevel: LocationPermissionLevel.locationWhenInUse);
      if (permissionResult == PermissionStatus.granted) {
        await Future.delayed(Duration(seconds: 1));
        setState(() {
          locationState = LocatePermissionState.success;
        });
      } else {
        var models = await SharedPreferenceTool.getCityModels();
        if (models == null || models.isEmpty) {
          Navigator.of(context).pushNamed(MyRouter.search);
        }
        ToastUtils.toastMsg("请打开定位权限", context, duration: 2);
      }
    } else {
      print("获取定位权限成功");
      setState(() {
        locationState = LocatePermissionState.success;
      });
    }
  }



  @override
  bool get wantKeepAlive => true;
}

enum LocatePermissionState {
  success,
  loading,
  failed,
}
